package org.daidai.abstrusewriting.homepage.fragments;


import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RadioGroup;

import org.daidai.abstrusewriting.R;
import org.daidai.abstrusewriting.fragments.BaseFragment;
import org.daidai.abstrusewriting.homepage.hot.adapters.FootPictureAdapter;
import org.daidai.abstrusewriting.homepage.hot.adapters.HeadPictureAdapter;
import org.daidai.abstrusewriting.homepage.hot.adapters.MyCommonAdapter;
import org.daidai.abstrusewriting.homepage.hot.adapters.MyHotItemAdapter;
import org.daidai.abstrusewriting.homepage.hot.client.ClientApi;
import org.daidai.abstrusewriting.homepage.hot.model.ADinformationData;
import org.daidai.abstrusewriting.homepage.hot.model.DiscoveryColumns;
import org.daidai.abstrusewriting.homepage.hot.model.EditorRecommendAlbums;
import org.daidai.abstrusewriting.homepage.hot.model.FocusImages;
import org.daidai.abstrusewriting.homepage.hot.model.Guess;
import org.daidai.abstrusewriting.homepage.hot.model.HotRecommends;
import org.daidai.abstrusewriting.homepage.hot.model.SpecialColumn;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * A simple {@link Fragment} subclass.
 */
public class HotFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, ViewPager.OnPageChangeListener, RadioGroup.OnCheckedChangeListener {

    private ViewPager headViewpager;
    private static List allList;
    private boolean flag1;
    private boolean flag2;
    private boolean flag3;
    private boolean flag4;
    private DiscoveryColumns discoveryColumns;
    private Guess guess;
    private EditorRecommendAlbums editorRecommendAlbums;
    private SpecialColumn specialColumn;
    static{
        allList = new ArrayList();
    }
    private boolean running;
    private RecyclerView myRecycleView;
    private ListView myListView;
    private SwipeRefreshLayout refresh;
    private MyCommonAdapter mAdapter;
    private RadioGroup mRadioGroup;
    private HeadPictureAdapter mHeadPictureAdapter;
    private List<FocusImages.SignImage> mSignImagesList;
    private Handler mHandler  = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 998:
                    int currentItem = headViewpager.getCurrentItem();
                    currentItem++;
                    headViewpager.setCurrentItem(currentItem);
                    break;
            }
        }
    };
    private ViewPager footViewpager;

    public HotFragment() {
        // Required empty public constructor
    }

    @Override
    public String getFragmentTitle() {
        return "HotFragment";
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ClientApi.getFirstJsonBody("http://mobile.ximalaya.com/mobile/discovery/v3/recommends?channel=and-a1&device=android&includeActivity=true&includeSpecial=true&scale=2&version=4.3.98");
        ClientApi.getSecondJsonBody("http://mobile.ximalaya.com/mobile/discovery/v1/recommend/hotAndGuess?device=android");
        ClientApi.getThirdJsonBody("http://adse.ximalaya.com/ting?device=android&name=find_banner&network=wifi&operator=0&version=4.3.98");
        EventBus.getDefault().register(this);
    }
    //TODO:EventBus 获取头部Viewpager图片数据
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getViewpagerImage(FocusImages focusImages){
        if (focusImages!=null) {
            mSignImagesList.addAll(focusImages.getSignImages());
            mHeadPictureAdapter.notifyDataSetChanged();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getDiscoveryColumns(DiscoveryColumns discoveryColumns){
        if (discoveryColumns!=null) {
            this.discoveryColumns = discoveryColumns;
            flag1=true;
            setAllList();
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getGuessItem(Guess guess){
        this.guess = guess;
        flag2=true;
        setAllList();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEditorRecommendAlbums(EditorRecommendAlbums editorRecommendAlbums){
        this.editorRecommendAlbums = editorRecommendAlbums;
        flag3=true;
        setAllList();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getSpecialColumn(SpecialColumn specialColumn){
        this.specialColumn = specialColumn;
        flag4=true;
        setAllList();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getHotRecommends(HotRecommends hotRecommends){
        if (hotRecommends!=null) {
            List<HotRecommends.HotItem> hotItems = hotRecommends.getHotItems();
            String title = hotItems.get(0).getTitle();
            MyHotItemAdapter adapter = new MyHotItemAdapter(getContext(),hotItems);
            myListView.setAdapter(adapter);
        }

    }

    public void setAllList(){
        if (flag1&&flag2&&flag3&&flag4){
            allList.clear();
            if (discoveryColumns!=null) {
                allList.add(discoveryColumns);
            }
            if (guess!=null) {
                allList.add(guess);
            }
            if (editorRecommendAlbums!=null) {
                allList.add(editorRecommendAlbums);
            }
            if (specialColumn!=null) {
                allList.add(specialColumn);
            }
            mAdapter.notifyDataSetChanged();
            refresh.setRefreshing(false);
            flag1 = flag2 =flag3 = flag4 = false;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getADinformation(ADinformationData aDinformationData){
        if (aDinformationData!=null) {
            //Log.d("hot", "getADinformation:" + aDinformationData.getADinformations().get(1).getCover());
            List<ADinformationData.ADinformation> list = aDinformationData.getADinformations();
            FootPictureAdapter adapter = new FootPictureAdapter(getContext(),list);
            footViewpager.setAdapter(adapter);
        }

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View ret = null;
        ret = inflater.inflate(R.layout.fragment_hot, container, false);
        headViewpager = (ViewPager) ret.findViewById(R.id.fragment_head_viewpager);
        mSignImagesList = new ArrayList<>();
        mHeadPictureAdapter = new HeadPictureAdapter(getContext(), mSignImagesList);
        headViewpager.setAdapter(mHeadPictureAdapter);
        footViewpager = (ViewPager) ret.findViewById(R.id.fragment_foot_viewpager);
        myRecycleView = ((RecyclerView) ret.findViewById(R.id.hotfragment_recycleview));
        refresh = ((SwipeRefreshLayout) ret.findViewById(R.id.hotfragment_refresh));
        myListView = ((ListView) ret.findViewById(R.id.hotfragment_listView));
        mRadioGroup = (RadioGroup) ret.findViewById(R.id.fragment_head_rg);
        mRadioGroup.check(R.id.rg_btn0);
        mAdapter = new MyCommonAdapter(allList,getContext());
        myRecycleView.setAdapter(mAdapter);
        if (myRecycleView!=null){
            RecyclerView.LayoutManager lm=new LinearLayoutManager(getContext(),
                    LinearLayoutManager.VERTICAL,false);
            myRecycleView.setLayoutManager(lm);
        }
        refresh.setOnRefreshListener(this);
        refresh.setColorSchemeColors(Color.BLACK,Color.YELLOW,Color.RED,Color.BLUE);
        mRadioGroup.setOnCheckedChangeListener(this);
        headViewpager.addOnPageChangeListener(this);
        final Thread thread = new Thread(){
            public void run() {
                running = true;
                while (running){
                   mHandler.sendEmptyMessage(998);
                    try {
                        Thread.sleep(4000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread.start();
        return ret;
    }

    @Override
    public void onDestroy() {
        running = false;
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onRefresh() {
        ClientApi.getFirstJsonBody("http://mobile.ximalaya.com/mobile/discovery/v3/recommends?channel=and-a1&device=android&includeActivity=true&includeSpecial=true&scale=2&version=4.3.98");
        ClientApi.getSecondJsonBody("http://mobile.ximalaya.com/mobile/discovery/v1/recommend/hotAndGuess?device=android");
        ClientApi.getThirdJsonBody("http://adse.ximalaya.com/ting?device=android&name=find_banner&network=wifi&operator=0&version=4.3.98");
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (mSignImagesList.size()>0) {
        //TODO : 根据Viewpager 选RadioButton
        switch (position%mSignImagesList.size()){
            case 0: mRadioGroup.check(R.id.rg_btn0);
                break;
            case 1: mRadioGroup.check(R.id.rg_btn1);
                break;
            case 2: mRadioGroup.check(R.id.rg_btn2);
                break;
            case 3: mRadioGroup.check(R.id.rg_btn3);
                break;
            case 4: mRadioGroup.check(R.id.rg_btn4);
                break;
            case 5: mRadioGroup.check(R.id.rg_btn5);
                break;
            case 6: mRadioGroup.check(R.id.rg_btn6);
                break;
        }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i){
            case R.id.rg_btn0:
                headViewpager.setCurrentItem(0);
                break;
            case R.id.rg_btn1:
                headViewpager.setCurrentItem(1);
                break;
            case R.id.rg_btn2:
                headViewpager.setCurrentItem(2);
                break;
            case R.id.rg_btn3:
                headViewpager.setCurrentItem(3);
                break;
            case R.id.rg_btn4:
                headViewpager.setCurrentItem(4);
                break;
            case R.id.rg_btn5:
                headViewpager.setCurrentItem(5);
                break;
            case R.id.rg_btn6:
                headViewpager.setCurrentItem(6);
                break;
        }
    }
}
